package net.zkbc.helloworld.util;

import java.util.ArrayList;
import java.util.List;
import java.util.Locale;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.MessageSource;
import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;

import net.zkbc.shared.protocol.OutputMessage;

public abstract class Validators {

	private static final Logger LOG = LoggerFactory.getLogger(Validators.class);

	/**
	 * 校验规则：登录密码最小长度
	 */
	public static final int RULE_PWD_MIN = 6;

	/**
	 * 校验规则：登录密码最大长度
	 */
	public static final int RULE_PWD_MAX = 16;

	/**
	 * 校验规则：登录密码正则表达式
	 */
	public static final String RULE_PWD_REGEXP = "^(?=.*[0-9]+.*)(?=.*[a-zA-Z]+.*)[0-9a-zA-Z]{" + RULE_PWD_MIN + ","
			+ RULE_PWD_MAX + "}$";

	/**
	 * 消息码：登录密码不正确
	 */
	public static final String CODE_PWD_ERROR = "Valid.UserService.changeMyLoginPassword.plainOldPassword";

	/**
	 * 添加参数校验错误到输出消息
	 * 
	 * @param output
	 * @param result
	 * @param messageSource
	 * @param locale
	 */
	public static void addParameterErrors(OutputMessage output, BindingResult result, MessageSource messageSource,
			Locale locale) {
		List<String> errors = new ArrayList<String>();
		for (FieldError error : result.getFieldErrors()) {
			String[] codes = error.getCodes();
			if (codes != null) {
				LOG.info("校验失败：{}", codes[0]);
			}
			errors.add(messageSource.getMessage(error, locale));
		}
		output.setParameterErrors(errors);
	}

	/**
	 * 添加参数校验错误码到输出消息
	 * 
	 * @param output
	 * @param code
	 * @param messageSource
	 * @param locale
	 */
	public static void addParameterErrors(OutputMessage output, String code, MessageSource messageSource,
			Locale locale) {
		LOG.info("校验失败：{}", code);
		if (code == null) {
			return;
		}
		output.setParameterErrors(messageSource.getMessage(code, null, code, locale));
	}

}
